package com.lapelittle.framework.interceptor;

import com.lapelittle.framework.entity.SysUserToken;
import com.lapelittle.framework.exception.AuthException;
import com.lapelittle.framework.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            throw new AuthException("token不能为空");
        }
        
        // 验证token
        SysUserToken tokenEntity = tokenService.validateToken(token);
        if (tokenEntity == null) {
            throw new AuthException("token已失效");
        }
        
        // 将用户ID存入request
        request.setAttribute("userId", tokenEntity.getUserId());
        return true;
    }
} 